import 'dart:async';

import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:shopping_group/baseblocs/bloc_provider.dart';
import 'package:shopping_group/event/event.dart';
import 'package:shopping_group/http/apis/apis.dart';
import 'package:shopping_group/http/http_request_all.dart';
import 'package:shopping_group/modle/login/entity/sv_entity.dart';
import 'package:shopping_group/utils/network_utils.dart';
import 'package:shopping_group/utils/route_util.dart';

class WxOpenIdBloc implements BlocBase {
  StreamController<Object> _codeController = StreamController<Object>();
  StreamSink get codeDate => _codeController.sink;

  StreamController<Object> _idController = StreamController<Object>();
  StreamSink get idDate => _idController.sink;

  WxOpenIdBloc() {
    _codeController.stream.listen(codeData);
    _idController.stream.listen(idData);
  }
  void idData(data) {
    _idTask(data);
  }

  void codeData(data) {
    _codeTask(data);
  }

  void _idTask(data) async {
    FocusScope.of(RouteUtil.navigatorKey.currentContext)
        .requestFocus(FocusNode());
    // BotToast.showLoading();
    NetworkUtils.isNetworkConnected(connectedCallback: (connected) {
      if (!connected) {
        BotToast.showText(text: '网络无法连接');
      } else {
        HttpUtilAll.get(Apis.AUTH_OPENID_URL, data: data, headers: {},
            success: (result) {
          BotToast.closeAllLoading();

          if (null != result) {
            // SvEntity svEntity = SvEntity.fromJson(result);
            eventBus.fire(GetWxOpenIdEvent(result, data['shopId']));
          }
        }, error: (errorMsg) {
          BotToast.closeAllLoading();
          // 请求失败返回的错误信息
          BotToast.showText(text: errorMsg);
        });
      }
    });
  }

  void _codeTask(data) async {
    FocusScope.of(RouteUtil.navigatorKey.currentContext)
        .requestFocus(FocusNode());
    // BotToast.showLoading();
    NetworkUtils.isNetworkConnected(connectedCallback: (connected) {
      if (!connected) {
        BotToast.showText(text: '网络无法连接');
      } else {
        HttpUtilAll.get(Apis.AUTH_CODE_URL, data: data, headers: {},
            success: (result) {
          BotToast.closeAllLoading();

          if (null != result) {
            SvEntity svEntity = SvEntity.fromJson(result);
            //BotToast.showText(text: 'svEntity=' + svEntity.toJson().toString());
            eventBus.fire(GetWxCodeUrlEvent(svEntity.val));
          }
        }, error: (errorMsg) {
          BotToast.closeAllLoading();
          // 请求失败返回的错误信息
          BotToast.showText(text: errorMsg);
        });
      }
    });
  }

  @override
  void dispose() {
    _codeController?.close();
    _idController?.close();
  }
}
